package com.rill.paging;

/**
 * 分页信息辅助类：静态方法返回Page的实例 1.分页信息中参数大多可通过计算得出，必要的参数：当前页、总记录、每页显示数
 */
public class PageUtil {
	public static Page createPage(int everyPage, int totalCount, int currentPage) {
		everyPage = getEveryPage(everyPage);
		currentPage = getCurrentPage(currentPage);
		int totalPage = getTotalPage(everyPage, totalCount);
		int beginIndex = getBeginIndex(everyPage, currentPage);
		boolean hasPrePage = getHasPrePage(currentPage);
		boolean hasNextPage = getHasNextPage(totalPage, currentPage);

		return new Page(everyPage, totalPage, totalCount, currentPage,
				beginIndex, hasPrePage, hasNextPage);
	}

	// 设置是否有上一页，需要当前页：只要不是第一页都会有下一页
	public static boolean getHasPrePage(int currentPage) {
		return currentPage == 1 ? false : true;
	}

	// 设置是否有下一个，需要总页数和当前页：最后一页或者总页数为0时没有
	public static boolean getHasNextPage(int totalPage, int currentPage) {
		return currentPage == totalPage || totalPage == 0 ? false : true;
	}

	// 设置起始点：需要每页显示多少，当前页
	public static int getBeginIndex(int everyPage, int currentPage) {

		return (currentPage - 1) * everyPage;// 当前页-1乘每页显示数
	}

	public static int getCurrentPage(int currentPage) {
		return currentPage == 0 ? 1 : currentPage;// 当前页为0时返回为1，否则为设置的
	}

	public static int getEveryPage(int everyPage) {
		return everyPage == 0 ? 10 : everyPage;// 如果为0默认每页10条，否则是自己设置的
	}

	public static int getTotalPage(int everyPage, int totalCount) {
		int totalPage = 0;
		if (totalCount % everyPage == 0) {// 整除
			totalPage = totalCount / everyPage;
		} else {// 非整除
			totalPage = totalCount / everyPage + 1;
		}
		return totalPage;
	}

	/**
	 * @param page
	 * @param totalCount
	 *  按照分页信息查询用户文章
	 */
	public static Page createPage(Page page, int totalCount) {
		int everyPage = getEveryPage(page.getEveryPage());
		int currentPage = getCurrentPage(page.getCurrentPage());
		int totalPage = getTotalPage(everyPage, totalCount);
		int beginIndex = getBeginIndex(everyPage, currentPage);
		boolean hasPrePage = getHasPrePage(currentPage);
		boolean hasNextPage = getHasNextPage(totalPage, currentPage);

		return new Page(everyPage, totalPage, totalCount, currentPage,
				beginIndex, hasPrePage, hasNextPage);
	}
}
